<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/9
 * Time: 16:12
 */

namespace bgb\office\excel;

use PhpOffice\PhpSpreadsheet\Cell\DataType;

class Excel
{

    const WRITE_MODE_APPEND = 'append'; //追加方式写入

    const WRITE_MODE_REWRITE = 'rewrite'; //覆盖重写

    /**
     * 读取excel
     * @param $file
     * @return array
     */
    public static function reader($file)
    {
        try {
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);

            return $reader->getActiveSheet()->toArray(null, true, true, false);

        } catch (\Exception $exception) {
            return [];
        }
    }

    /**
     * 写入excel
     * @param $file
     * @param array $data 二维数组
     * @param string $mode
     * @return bool
     */
    public static function writer($file, array $data = [], $mode = self::WRITE_MODE_APPEND)
    {
        try {

            if (!is_file($file) || $mode == self::WRITE_MODE_REWRITE) {
                $_file = __DIR__ . '/default.xlsx';
            } else {
                $_file = $file;
            }

            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($_file);

            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);

            $maxHeight = 0;

            //追加模式
            /*if ($mode == self::WRITE_MODE_APPEND) {
                $maxHeight = $spreadsheet->getActiveSheet()->getHighestRow();
            }*/

            $data = array_values($data);

            foreach ($data as $key => $value) {
                $row = $maxHeight + $key + 1;
                $value = array_values($value);
                foreach ($value as $k => $v) {
                    $spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($k + 1, $row, DataType::checkString($v)); //防止科学计数法
                }
            }

            $writer->save($file);
            return true;
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
    }

}